const express = require('express');
const expressStatic = require('express-static');
const consolidate = require('consolidate');
const getData = require('./myModules/upData');
const readFile = require('./myModules/readFile');
const getLyric = require('./myModules/getLyrics');
const cookieParser = require('cookie-parser');
const fs = require('fs');
///
getData();



let NOC = 0; // Number Of Connection 连接次数
let musicData = readFile('./Data/musicData.json');
let comments = readFile('./Data/comments.json');
let user= readFile('./Data/userData.json');
let userData = user.email;
let userNum =  user.number;
console.log(userData)

const app = express();
   app.listen(4396,()=>{
    NOC++;
   console.log(`hello，第${NOC}位客人`);
})
 
      app.use('/index',function(req, res){
 
        res.render('index.ejs',{data:musicData, comments:comments });
      })
       //database
       app.use('/database', function(req, res){
         if(req.query.user === 'admin'&& req.query.password === 'clearlove'){
         res.send(musicData);
     
        }
        else{
          res.writeHead(500);
          res.end('管理员或密码错误');
        }
       })
       ///updata 更新曲库
       app.use('/updata', (req, res)=>{
        if(req.query.user === 'admin'&& req.query.password === 'clearlove'){
          getData();
          musicData = readFile('./Data/musicData.json');
          res.writeHead(200,{'content-Type':'text/html'})
          res.end(' updata music successful ');
         }
       })

       ///lyrics
      app.use('/lyrics', function(req, res){
        if(req.query.user === 'admin'&& req.query.password === 'clearlove'){
         ///模块引用
         getLyric(res, req.query.id)
       
         }
         else{
           res.writeHead(500);
           res.end('管理员或密码错误');
         }
      })
      ///video
      app.use('/videoData', function(req, res){
        
        if(req.query.user === 'admin'&& req.query.password === 'clearlove'){
          ///模块引用
          let filename = __dirname + '/Data/database.json';
           fs.stat(filename, function(err, data){
             if(err){
               res.writeHead(500);
               res.end('链接错误');
             }
             else{
                let videoData = fs.readFileSync(filename);

                json = videoData;
                let buf = new Buffer.from(json);
                json = JSON.parse(buf);
            
                res.send(json.video);
              }
           })
          }
          else{
            res.writeHead(500);
            res.end('管理员或密码错误');
          }
      })
      ////comments
          app.use('/comment', (req, res)=>{
              if(req.query.act == 'upload'){
              let data = {
                "name":req.query.user,
                'content':req.query.data
              }
             console.log(req.query.user)
              comments.comments.unshift(data)
              if(  comments.comments.length > comments.quantity){
                comments.comments.pop();
        
              }
   
                 fs.writeFile('./Data/comments.json', JSON.stringify(comments) ,()=>{
            
               
              })
              res.end();
              }
              else if(req.query.act == 'load'){
    
                let commentData = [];
                let start = parseInt(req.query.order);
                let end =  parseInt(req.query.order) + parseInt(comments.order);
                if(end > comments.comments.length){
                  end = comments.comments.length;
                }
                for( let i=start; i< end; i++  ){
                  commentData.push(comments.comments[i]);
                }
                res.send(commentData)
              }
        
          })
      
 ///login
         //cookie-parser
          app.use(cookieParser('asd45%%$4$$clearloveqweoqpwesdas'));
       
          app.get('/login',(req, res)=>{
           if(req.query.act == 'login'){
            if(userData[req.query.email] && userData[req.query.email].password == req.query.password){
              res.send(true);
            }
            else{
              res.send(false);
            }
           }
           else if(req.query.act == 'registered'){
            if(userData[req.query.email]){
              res.send({'act':false, mes:'邮箱已被注册'})
            }
            else{     
              userData[req.query.email] = {
                'password': req.query.password
              }
              userNum++;
              fs.writeFile('./Data/userData.json', JSON.stringify({"number":userNum,"email":userData}) ,()=>{

             console.log(userData)
            })
                   res.send({'act':true, mes:'注册成功'}); 
            }

           }
    
          })

        ///ejs模板使用
        app.set('view engine','html');
        app.set('views', './template');
        app.engine('html', consolidate.ejs);
        ///配置静态文件目录
        app.use(expressStatic('./public'));


       // https://api.imjad.cn/cloudmusic/?type=artist&id=12057022
